package com.greatchn.single_login.web.srv;

import cn.hutool.core.util.IdUtil;
import com.greatchn.single_login.util.ServiceAssert;
import com.greatchn.single_login.web.po.Token;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @LoginSrv: login srv
 * @author: ZBoHang
 * @time: 2023/2/8 11:48
 */
@Service
public class LoginSrv {

    public static ConcurrentHashMap<String, Token> map = new ConcurrentHashMap<>(16);

    public String createToken(String userName) {
        // TODO: 2023/2/8
        long expires = System.currentTimeMillis() + 1000L * 120;
        String tokenKey = IdUtil.fastSimpleUUID();
        map.put(tokenKey, new Token().setKey(tokenKey).setExpires(expires).setUserName(userName));
        return tokenKey;
    }

    /**
     * get token
     */
    public Token getTokenByTokenKey(String tokenKey) {
        return map.get(tokenKey);
    }

    /**
     * true-有效 false-无效
     */
    public Boolean checkToken(String tokenKey) {
        // TODO: 2023/2/8
        Token token = map.get(tokenKey);
        ServiceAssert.notNull(token, "令牌无效!");

        long currentTimeMillis = System.currentTimeMillis();

        return currentTimeMillis > token.getExpires() ? Boolean.FALSE : Boolean.TRUE;
    }
}
